package com.njupt.StringProblem;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author: wujiaming
 * @CreateTime: 2025/3/7 10:17
 * @Description:3. 无重复字符的最长子串
 * @Version: 1.0
 */


public class LengthOfLongestSubstring_3 {

    /**
     * 暴力解超时
     * @param s
     * @return
     */
    public int lengthOfLongestSubstring1(String s) {
        int max = 0;
        int len = s.length();
        for (int i = 0; i < len; i++) {
            for (int j = i; j <len ; j++) {
                String sub = s.substring(i,j+1);
                if(isContain(sub)){
                    if(sub.length() > max){
                        max = sub.length();
                    }
                }
            }
        }
        return max;
    }

    /**
     * 滑动窗口法
     * @param s
     * @return
     */
    public int lengthOfLongestSubstring(String s) {
        int len = s.length();
        int max = 0;
        int left = 0;
        int right = 0;
        while(left <= right && right < len){
            String sub = s.substring(left,right +1);
            if(isContain(sub)){
                if(sub.length() > max){
                    max = sub.length();
                }
                right++;
            }else {
                left++;
            }
        }
        return max;
    }

    private boolean isContain(String sub) {

        Set<Character> set = new HashSet<>();
        for (int i = 0; i < sub.length(); i++) {
            set.add(sub.charAt(i));
        }
        return sub.length() == set.size();
    }


    public static void main(String[] args) {
        String str = "bbbbb";
        LengthOfLongestSubstring_3 test = new LengthOfLongestSubstring_3();
        System.out.println(test.lengthOfLongestSubstring(str));
    }
}
